import json
from datetime import datetime

from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods

from resource.models import Resource
# 处理地址数据 ============================================
from .models import *
from django.views import View
from django.core.paginator import Paginator


# 信息查询
class AddressSearch(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            pageNum = data['pageNum']  # 当前页
            pageSize = data['pageSize']  # 每页大小
            city = data['city']
            county = data['county']
            town = data['town']

            queryset = Address.objects.all().order_by('city', 'county','town')

            # 先构建基础查询条件（必选条件：city）
            if city:
                queryset = queryset.filter(city__in=city)
            if county:  # 如果county列表有元素（非空）
                queryset = queryset.filter(county__in=county)
            if town:  # 如果county列表有元素（非空）
                queryset = queryset.filter(town__in=town)

            # 获取查询集
            total = queryset.count()

            # 分页
            paginator = Paginator(queryset, pageSize)
            dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            serializer = AddressSerializer(dataPage.object_list, many=True)

            print('ParamSerializer data:', serializer.data)

            return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })


# 获取数据列表
@require_http_methods(["GET"])
def addressList(request):
    response = {}
    try:
        items = Address.objects.all()
        item_list = []

        for item in items:
            resources = Resource.objects.all().filter(address=item)
            item_list.append({
                'id': item.id,
                'province': item.province,
                'city': item.city,
                'county': item.county,
                'town': item.town,
                'village': item.village,
                'detail': item.detail,
                'resource_count': len(resources)  # 计算关联的资源数量
            })
        response['msg'] = 'Get address list success!'
        response['code'] = 200
        response['data'] = item_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 新增
@csrf_exempt
@require_http_methods(["GET", "POST"])
def addressAdd(request):
    response = {}
    item = Address()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断地址是否已存在
        if Address.objects.filter(province=data.get('province'),
                                  city=data.get('city'),
                                  county=data.get('county'),
                                  town=data.get('town'),
                                  village=data.get('village'),
                                  detail=data.get('detail')).exists():
            response['msg'] = '该地址已存在！'
            response['code'] = 500
            return JsonResponse(response)

        item.province = data.get('province')
        item.city = data.get('city')
        item.county = data.get('county')
        item.town = data.get('town')
        item.village = data.get('village')
        item.detail = data.get('detail')

        item.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 修改
@csrf_exempt
@require_http_methods(["GET", "POST"])
def addressUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断地址是否已存在
        if Address.objects.filter(id=data.get('id')).exists():
            item = Address.objects.get(id=data.get('id'))
            item.province = data.get('province')
            item.city = data.get('city')
            item.county = data.get('county')
            item.town = data.get('town')
            item.village = data.get('village')
            item.detail = data.get('detail')

            item.save()  # 只更新指定字段
            response['msg'] = '更新成功！'
            response['code'] = 200
        else:
            response['msg'] = '该地址已经不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


# 删除
@require_http_methods(["GET", "POST"])
def addressDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = Address.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'Address deleted successfully!'
        response['code'] = 200
    except Address.DoesNotExist:
        response['msg'] = 'Address not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理角色数据 ============================================

@require_http_methods(["GET"])
def roleList(request):
    response = {}
    try:
        roles = Role.objects.all()
        role_list = []

        for role in roles:
            users = User.objects.all().filter(role=role)
            role_list.append({
                'id': role.id,
                'name': role.name,
                'code': role.code,
                'status': role.status,
                'user_count': len(users),  # 计算关联的资源数量
                'create_time': role.create_time,
                'update_time': role.update_time,
                'remark': role.remark
            })
        response['msg'] = 'Get role list success!'
        response['code'] = 200
        response['data'] = role_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def roleAdd(request):
    response = {}
    role = Role()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 新增判断角色是否已存在
        if Role.objects.filter(name=data['name']).exists() or Role.objects.filter(code=data['code']).exists():
            response['msg'] = '该角色已存在！'
            response['code'] = 500
            return JsonResponse(response)

        role.name = data['name']
        role.code = data['code']
        role.create_time = datetime.now().date()

        role.save()
        response['msg'] = '添加成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def roleUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 判断角色是否已存在
        if Role.objects.filter(id=data['id']).exists():
            role = Role.objects.get(id=data['id'])
            role.name = data['name']
            role.code = data['code']
            role.status = True if data['status'].lower() == "true" else False

            role.save(update_fields=['name', 'code', 'status'])  # 只更新指定字段
            response['msg'] = 'Role info update success'
            response['code'] = 200
        else:
            response['msg'] = '该角色不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


@require_http_methods(["GET", "POST"])
def roleDelete(request):
    response = {}
    try:
        role_id = None
        if request.method == 'GET':
            role_id = request.GET['id']
        elif request.method == 'POST':
            role_id = request.POST['id']

        if not role_id:
            response['msg'] = 'The ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        role = Role.objects.get(id=role_id)
        role.delete()
        response['msg'] = 'Role deleted successfully!'
        response['code'] = 200
    except Role.DoesNotExist:
        response['msg'] = 'Role not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 处理用户数据 ============================================
# 信息查询
class UserSearch(View):
    def post(self, req):
        try:
            data = json.loads(req.body.decode('utf-8'))

            pageNum = data['pageNum']  # 当前页
            pageSize = data['pageSize']  # 每页大小
            city = data['city']
            county = data['county']
            town = data['town']

            queryset = User.objects.all().order_by('username')

            # 先构建基础查询条件（必选条件：city）
            # if city:
            #     queryset = queryset.filter(username__in=city)

            # 获取查询集
            total = queryset.count()

            # 分页
            paginator = Paginator(queryset, pageSize)
            dataPage = paginator.page(pageNum)

            # 序列化数据 - 传递查询集给序列化器
            serializer = UserSerializer(dataPage.object_list, many=True)

            print('Serializer data:', serializer.data)

            return JsonResponse({'code': 200, 'data': serializer.data, 'total': total})
        # 捕获其他未预料的异常（作为兜底）
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'msg': f'服务器错误：{str(e)}'  # 生产环境可简化为"服务器内部错误"
            })

@csrf_exempt
@require_http_methods(["GET", "POST"])
def userAdd(request):
    response = {}
    user = User()
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET

        # 获取角色
        role_obj = Role.objects.get(id=data.get('role'))

        user.username = data.get('username')
        user.password = data.get('password')
        user.phone = data.get('phone')
        user.email = data.get('email', '')
        user.nickname = data.get('nickname', '')
        user.create_time = datetime.now().date()
        user.role = role_obj

        user.save()
        response['msg'] = '添加用户成功！'
        response['code'] = 200

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception')
    return JsonResponse(response)


@require_http_methods(["GET"])
def userList(request):
    response = {}
    try:
        users = User.objects.all()
        user_list = []
        # 遍历用户列表，构建返回数据
        for user in users:
            user_list.append({
                'id': user.id,
                'username': user.username,
                'password': user.password,
                'phone': user.phone,
                'email': user.email,
                'nickname': user.nickname,
                # 只返回角色id和角色名称，避免序列化整个Role对象
                # 'role_id': user.role.id if user.role else None,
                'role': user.role.name if user.role else None,
                'status': user.status,
                'created_time': user.created_time.strftime('%Y-%m-%d')
            })
        response['msg'] = 'Get user list success!'
        response['code'] = 200
        response['data'] = user_list
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    print(response)
    return JsonResponse(response)


@require_http_methods(["GET", "POST"])
def getUserById(request):
    response = {}
    try:
        user_id = None
        if request.method == 'GET':
            user_id = request.GET.get('id')
        elif request.method == 'POST':
            user_id = request.POST.get('id')

        if not user_id:
            response['msg'] = 'User ID is required'
            response['code'] = 500
            return JsonResponse(response)

        user = User.objects.get(id=user_id)
        response['msg'] = 'Get user success!'
        response['code'] = 200
        response['user'] = {
            'id': user.id,
            'username': user.username,
            'phone': user.phone,
            'email': user.email,
            'nickname': user.nickname,
            # 只返回角色id和角色名称
            'role': user.role.description if user.role else None,
            'created_time': user.created_time.strftime('%Y-%m-%d %H:%M:%S')
        }
    except User.DoesNotExist:
        response['msg'] = 'User not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


@csrf_exempt
@require_http_methods(["GET", "POST"])
def userUpdate(request):
    response = {}
    try:
        data = None
        if request.method == 'POST':
            # 根据Content-Type解析数据
            if request.content_type == 'application/json':
                data = json.loads(request.body)
            else:
                data = request.POST
        elif request.method == 'GET':
            data = request.GET
        print(data, data.get('role'))
        # 判断是否已存在
        if User.objects.filter(id=data.get('id')).exists():
            user = User.objects.get(id=data.get('id'))
            user.username = data.get('username')
            user.phone = data.get('phone')
            user.email = data.get('email')
            user.nickname = data.get('nickname')
            user.role = Role.objects.get(id=data.get('role')) if data.get('role') else None
            user.status = True if data.get('status').lower() == "true" else False

            user.save()  # 只更新指定字段
            response['msg'] = 'User info update success'
            response['code'] = 200
        else:
            response['msg'] = '该用户不存在！'
            response['code'] = 500
            return JsonResponse(response)

    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
        print('Exception：', e)
    return JsonResponse(response)


@require_http_methods(["GET", "POST"])
def userDelete(request):
    response = {}
    try:
        del_id = None
        if request.method == 'GET':
            del_id = request.GET.get('id')
        elif request.method == 'POST':
            del_id = request.POST.get('id')

        if not del_id:
            response['msg'] = 'User ID is required!'
            response['code'] = 500
            return JsonResponse(response)

        item = User.objects.get(id=del_id)
        item.delete()
        response['msg'] = 'User deleted successfully!'
        response['code'] = 200
    except User.DoesNotExist:
        response['msg'] = 'User not found!'
        response['code'] = 500
    except Exception as e:
        response['msg'] = str(e)
        response['code'] = 500
    return JsonResponse(response)


# 登录 ====================================================

from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from .serializers import LoginSerializer
from rest_framework_jwt.settings import api_settings


@api_view(['POST'])
@permission_classes([AllowAny])
def userLogin(request):
    if request.method == 'POST':
        serializer = LoginSerializer(data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data['user']
            # login(request, user)

            # 获取或创建token
            # token, created = Token.objects.get_or_create(user=user)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 将用户对象传递进去，获取到该对象的属性值
            payload = jwt_payload_handler(user)
            # 将属性值编码成jwt格式的字符串
            token = jwt_encode_handler(payload)
            # 序列化用户数据
            user_data = UserSerializer(user).data

            return Response({
                'code': 200,
                'msg': '登录成功！',
                'token': token,
                'user': user_data
            }, status=status.HTTP_200_OK)

        return Response({
            'code': 500,
            'msg': serializer.errors['non_field_errors'][0] if 'non_field_errors' in serializer.errors else '登录失败！'
        }, status=status.HTTP_200_OK)
